package com.shuimin.group;

import com.shuimin.group.exception.ParamException;
import com.shuimin.group.mid.message.MessageBuilder;
import com.shuimin.group.model.weixin.WeixinUser;
import com.shuimin.group.service.WeixinUserService;
import com.shuimin.group.service.WeixinService;
import com.shuimin.group.util.*;
import io.netty.util.CharsetUtil;
import org.jdom.JDOMException;
import pond.common.S;
import pond.common.STREAM;
import pond.common.STRING;
import pond.web.Render;
import pond.web.Router;
import java.io.IOException;
import java.util.*;

public class WEIXIN extends Router {
    {
        get("/", (req, resp) -> {
            String signature = req.param("signature");//微信加密签名
            String timestamp = req.param("timestamp");// 时间戳
            String nonce = req.param("nonce");// 随机数
            String echostr = req.param("echostr");// 随机字符串
            if (STRING.isBlank(signature)
                    || STRING.isBlank(timestamp)
                    || STRING.isBlank(nonce)
                    || STRING.isBlank(echostr) )
            {
                resp.render(Render.text(""));
            }
            List<String> params = new ArrayList();
            params.add(WeixinService.TOKEN);
            params.add(timestamp);
            params.add(nonce);
            // 1. 将token、timestamp、nonce三个参数进行字典序排序
            Collections.sort(params, String::compareTo);
            // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
            String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));
            if (temp.equals(signature)) {
                resp.render(Render.text(echostr));
            } else
                resp.render(Render.text(""));
        });
        post("/", (req, resp) -> {
            try {
                Map<String, String> params = XMLUtil.doXMLParse(STREAM.readFully(req.in(), CharsetUtil.UTF_8));
                String receivedMsgType = params.get("MsgType");
                S.echo("receivedMsgType="+receivedMsgType);
                if (STRING.notBlank(receivedMsgType)) {
                    if (MessageBuilder.MSG_TYPE_TEXT.equals(receivedMsgType)) {
                        //根据获得的字段进行回复
                        String param = params.get("Content");
                        if (STRING.notBlank(param)) {
//                            WeixinService.out(MessageBuilder.buildTextMessage(param,params), resp);
                        } else {
                            //处理非关键字操作
                        }

                    }
                    else if (MessageBuilder.MSG_TYPE_EVENT.equals(receivedMsgType)) {
                        String eventType = params.get("Event");
                        if (STRING.notBlank(eventType) && MessageBuilder.MSG_TYPE_EVENT_SUBSCRIBE.equals(eventType)) {
                            String openId = params.get("FromUserName");
                            S.echo("openId:"+ openId);
                            Map<String,Object> userInfo = WeixinService.getUser(openId);
                            WeixinUserService.mergeObj(openId,userInfo);
                            resp.send(200);
                        }
                        else if (STRING.notBlank(eventType) && MessageBuilder.MSG_TYPE_EVENT_UNSUBSCRIBE.equals(eventType)) {
                            String openId = params.get("FromUserName");
                            S.echo("openId:"+ openId);
                            WeixinUser newWeixinUser = WeixinUserService.get( openId);
                            if (newWeixinUser != null)
                            {
                                newWeixinUser.set("subscribe_time", "0");
                                WeixinUserService.update( newWeixinUser);
                            }
                            resp.send(200);
                        }
                        else {
                            resp.send(200);
                        }
                    }
                } else {
                    resp.send(200);
                }
            } catch (JDOMException | IOException e) {
                e.printStackTrace();
            } catch (ParamException e) {
                resp.send(404,e.getMessage());
            }

        });
    }
}
